package com.bac.rentmap.web.tag.user.review;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Logger;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.bac.rentmap.web.filter.OriginalRequestUrlHolder;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class LoginReviewUrlTag extends SimpleTagSupport {
    private static final Logger log = Logger.getLogger(LoginReviewUrlTag.class
            .getName());

    private String reviewUrl;
    private Long flatAdId;

    @Override
    public void doTag() throws JspException, IOException {
        UserService userService = UserServiceFactory.getUserService();
        String res;
        if (userService.isUserLoggedIn()) {
            res = reviewUrl;
        } else {
            String loginUrl = reviewUrl;
            if (loginUrl.contains("?")) {
                loginUrl += "&";
            } else {
                loginUrl += "?";
            }
            
            loginUrl += "flatAdId=" + flatAdId + "&redirectUrl="
                    + buildRedirectUrl();
            res = userService.createLoginURL(loginUrl);
        }
        log.finest("URL: " + res);
        getJspContext().getOut().print(res);
    }
    
    private String buildRedirectUrl() throws UnsupportedEncodingException{
        String url = OriginalRequestUrlHolder.getUrl();
        if(!url.contains("loggedIn=true")){
          if(url.contains("?")){
              url += "&";
          }
          else{
              url += "?";
          }
          url += "loggedIn=true";
        }
        return URLEncoder.encode(url, "UTF-8");
    }

    public void setReviewUrl(String reviewUrl) {
        this.reviewUrl = reviewUrl;
    }

    public String getReviewUrl() {
        return reviewUrl;
    }

    public Long getFlatAdId() {
        return flatAdId;
    }

    public void setFlatAdId(Long flatAdId) {
        this.flatAdId = flatAdId;
    }
}
